package cat.joronya.supermanager.service.substrImpl;

import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cat.joronya.supermanager.privateleague.PrivateLeague;
import cat.joronya.supermanager.service.PrivateLeaguesParser;
import cat.joronya.supermanager.team.Team;

public class PrivateLeaguesParserImpl implements PrivateLeaguesParser
{
	protected ArrayList<PrivateLeague> privateLeagues;
	
	// start no private leagues text
	public static final String START_NO_PL = "En estos momentos no tienes ningún equipo participando en Ligas Privadas.";
	
	// start position
	public static final String START_POSITION_STRING = "background=\"gif/ligaprivada.gif\"";
	public static final String STOP_POSITION_STRING = "background=\"gif/ligasabajo.gif\"";
	
	// start tr
	public static final String START_TR = "<tr>";
	public static final String STOP_TR = "</tr>";
	
	// last tr
	public static final String START_LAST_TR = "colspan=\"4\"";
	
	// start id_priv
	public static final String START_IDPRIV = "<a href=\"verprivada.php?id_pri=";
	public static final String START_NAME = "\">";
	public static final String STOP_NAME = "</a></td>";
	
	// start pl teams
	public static final String START_PLTEAMS = "<td height=\"25\" class=\"gris\">";
	public static final String STOP_PLTEAMS = "</td>";
	
	// start jornada
	public static final String START_DAY = " - Jornada ";
	public static final String STOP_DAY = "</b>";
	
	// start position detall
	public static final String START_DPOSITION = "background=\"gif/clasificacionpos.gif\"";
	public static final String STOP_DPOSITION = "background=\"gif/clasificacionpie.gif\"";
	
	// start team name and manager (city)
	public static final String START_TEAM = "class=\"marengo\">";
	public static final String STOP_TEAM = "</td>";
	
	// start poins 
	public static final String START_VALUE = "class=\"marengobder\" align=\"right\">";
	public static final String STOP_VALUE = "<img";
	
	
	public ArrayList<PrivateLeague> getPrivateLeagues() 
	{
		return privateLeagues;
	}

	public long parse(String html)
			throws Exception 
	{
		long start = System.nanoTime();
		
		privateLeagues = new ArrayList<PrivateLeague>();
		
		// comprovem que hi hagin equips
		if( html.indexOf(START_NO_PL) == -1 )
		{
			int startPosition = html.indexOf(START_POSITION_STRING);
			if( startPosition == -1 )
				throw new Exception();

			int stopPosition = html.indexOf(STOP_POSITION_STRING);

			// recorrem els tr
			int startTr, stopTr;
			startTr = html.indexOf(START_TR, startPosition);
			while( startTr != -1 && startTr < stopPosition )
			{
				// recuperem tr
				stopTr = html.indexOf(STOP_TR, startTr);
				String tr = html.substring(startTr, stopTr);
				
				// is last tr?
				if( tr.indexOf(START_LAST_TR) != -1)
					break;
				
				// id_priv
				int startIdpriv = tr.indexOf(START_IDPRIV);
				int stopIdpriv = tr.indexOf(START_NAME, startIdpriv+START_IDPRIV.length());
				String idpriv = tr.substring(startIdpriv+START_IDPRIV.length(), stopIdpriv);

				// name
				int stopName = tr.indexOf(STOP_NAME,stopIdpriv+START_NAME.length());
				String name = tr.substring(stopIdpriv+START_NAME.length(), stopName);
				
				// teams in pl
				int startTeams = tr.indexOf(START_PLTEAMS, stopName+STOP_NAME.length());
				int stopTeams = tr.indexOf(STOP_PLTEAMS, startTeams+START_PLTEAMS.length());
				String plTeams = tr.substring(startTeams+START_PLTEAMS.length(), stopTeams);

				PrivateLeague pl = new PrivateLeague();
				pl.setId(idpriv);
				pl.setName(name);
				pl.setNumberOfTeams(plTeams);
				
				// guardem al llistat de private leagues
				privateLeagues.add(pl);
				
				// recuperem seguent startTr
				startTr = html.indexOf(START_TR, stopTr);
			}
		}
		return System.nanoTime()-start;
	}

	public long parseTeams(String html, PrivateLeague privateLeague) throws Exception
	{
		long start = System.nanoTime();
		
		HashMap<String, Team> teams = new HashMap<String, Team>();
		NumberFormat nf = NumberFormat.getInstance(new Locale("es", "ES"));
		
		// cerquem dia
		int startDay = html.indexOf(START_DAY);
		int stopDay = html.indexOf(STOP_DAY, startDay+START_DAY.length());
		String dayString = html.substring(startDay+START_DAY.length(), stopDay);
		int day = Integer.valueOf(nf.parse(dayString).intValue()).intValue();
		
		int startPosition = html.indexOf(START_DPOSITION);
		if( startPosition == -1 )
			throw new Exception();

		int stopPosition = html.indexOf(STOP_DPOSITION);

		// recorrem els tr, saltem header
		int startTr, stopTr;
		startTr = html.indexOf(START_TR, startPosition);
		while( startTr != -1 && startTr < stopPosition )
		{
			// recuperem tr
			stopTr = html.indexOf(STOP_TR, startTr);
			String tr = html.substring(startTr, stopTr);
			
			// ultim tr?
			if( tr.indexOf(STOP_DPOSITION) != -1 )
				break;
			
			// team name
			int startName = tr.indexOf(START_TEAM);
			int stopName = tr.indexOf(STOP_TEAM, startName+START_TEAM.length());
			String name = tr.substring(startName+START_TEAM.length(), stopName);
			
			// creem equip per omplir-lo
			Team t = new Team();
			t.setName(name.trim());
			t.setDay(day);
			
			// manager/city
			int startManagerCity = tr.indexOf(START_TEAM, stopName+STOP_TEAM.length());
			int stopManagerCity = tr.indexOf(STOP_TEAM, startManagerCity+START_TEAM.length());
			String managerCity = tr.substring(startManagerCity+START_TEAM.length(), stopManagerCity);
			
			String manager = "unknown";
			String city = "unknown";
			Pattern p = Pattern.compile("([^\\(]*)\\(([^\\)]*)\\)");
			Matcher m = p.matcher(managerCity);
			if (m.find()) {
				manager = m.group(1);
				city = m.group(2);
			}
			t.setManager(manager.trim());
			t.setCity(city.trim());
			
			// points
			int startValue = tr.indexOf(START_VALUE, stopManagerCity+STOP_TEAM.length());
			int stopValue = tr.indexOf(STOP_VALUE, startValue+START_VALUE.length());
			String value = tr.substring(startValue+START_VALUE.length(), stopValue);
			
			Float points;
			try {
				points = Float.valueOf(nf.parse(value).floatValue());
			} catch (ParseException pe) {
				points = Float.valueOf("0");
			}
			t.setPoints(points);
			
			// guardem l'equip parsejat al HashMap
			teams.put(name.trim(), t);
			
			// recuperem seguent startTr
			startTr = html.indexOf(START_TR, stopTr);
		}

		// al primer parseig guardem l'array de teams a la private league
		privateLeague.setTeams(teams);
		
		return System.nanoTime()-start;
	}
	
	public long parseGeneralTeams(String html, PrivateLeague privateLeague) throws Exception 
	{
		long start = System.nanoTime();
		
		HashMap<String, Team> teams = privateLeague.getTeams();
		NumberFormat nf = NumberFormat.getInstance(new Locale("es", "ES"));
		
		int startPosition = html.indexOf(START_DPOSITION);
		if( startPosition == -1 )
			throw new Exception();

		int stopPosition = html.indexOf(STOP_DPOSITION);

		// recorrem els tr, saltem header
		int startTr, stopTr;
		startTr = html.indexOf(START_TR, startPosition);
		while( startTr != -1 && startTr < stopPosition )
		{
			// recuperem tr
			stopTr = html.indexOf(STOP_TR, startTr);
			String tr = html.substring(startTr, stopTr);
			
			// ultim tr?
			if( tr.indexOf(STOP_DPOSITION) != -1 )
				break;
			
			// team name
			int startName = tr.indexOf(START_TEAM);
			int stopName = tr.indexOf(STOP_TEAM, startName+START_TEAM.length());
			String name = tr.substring(startName+START_TEAM.length(), stopName);
			
			// creem equip per omplir-lo
			Team t = teams.get(name.trim());
			
			// manager/city
			int startManagerCity = tr.indexOf(START_TEAM, stopName+STOP_TEAM.length());
			int stopManagerCity = tr.indexOf(STOP_TEAM, startManagerCity+START_TEAM.length());
			String managerCity = tr.substring(startManagerCity+START_TEAM.length(), stopManagerCity);
			
			String manager = "unknown";
			String city = "unknown";
			Pattern p = Pattern.compile("([^\\(]*)\\(([^\\)]*)\\)");
			Matcher m = p.matcher(managerCity);
			if (m.find()) {
				manager = m.group(1);
				city = m.group(2);
			}
			t.setManager(manager.trim());
			t.setCity(city.trim());
			
			// points
			int startValue = tr.indexOf(START_VALUE, stopManagerCity+STOP_TEAM.length());
			int stopValue = tr.indexOf(STOP_VALUE, startValue+START_VALUE.length());
			String value = tr.substring(startValue+START_VALUE.length(), stopValue);
			
			Float general;
			try {
				general = Float.valueOf(nf.parse(value).floatValue());
			} catch (ParseException pe) {
				general = Float.valueOf("0");
			}
			t.setGeneral(general);
			
			// recuperem seguent startTr
			startTr = html.indexOf(START_TR, stopTr);
		}

		//privateLeague.setTeams(teams);
		
		return System.nanoTime()-start;
	}

	public long parseBrokerTeams(String html, PrivateLeague privateLeague)throws Exception 
	{
		long start = System.nanoTime();
		
		HashMap<String, Team> teams = privateLeague.getTeams();
		NumberFormat nf = NumberFormat.getInstance(new Locale("es", "ES"));
		
		int startPosition = html.indexOf(START_DPOSITION);
		if( startPosition == -1 )
			throw new Exception();

		int stopPosition = html.indexOf(STOP_DPOSITION);

		// recorrem els tr, saltem header
		int startTr, stopTr;
		startTr = html.indexOf(START_TR, startPosition);
		while( startTr != -1 && startTr < stopPosition )
		{
			// recuperem tr
			stopTr = html.indexOf(STOP_TR, startTr);
			String tr = html.substring(startTr, stopTr);
			
			// ultim tr?
			if( tr.indexOf(STOP_DPOSITION) != -1 )
				break;
			
			// team name
			int startName = tr.indexOf(START_TEAM);
			int stopName = tr.indexOf(STOP_TEAM, startName+START_TEAM.length());
			String name = tr.substring(startName+START_TEAM.length(), stopName);
			
			// creem equip per omplir-lo
			Team t = teams.get(name.trim());
			
			// manager/city
			int startManagerCity = tr.indexOf(START_TEAM, stopName+STOP_TEAM.length());
			int stopManagerCity = tr.indexOf(STOP_TEAM, startManagerCity+START_TEAM.length());
			String managerCity = tr.substring(startManagerCity+START_TEAM.length(), stopManagerCity);
			
			String manager = "unknown";
			String city = "unknown";
			Pattern p = Pattern.compile("([^\\(]*)\\(([^\\)]*)\\)");
			Matcher m = p.matcher(managerCity);
			if (m.find()) {
				manager = m.group(1);
				city = m.group(2);
			}
			t.setManager(manager.trim());
			t.setCity(city.trim());
			
			// points
			int startValue = tr.indexOf(START_VALUE, stopManagerCity+STOP_TEAM.length());
			int stopValue = tr.indexOf(STOP_VALUE, startValue+START_VALUE.length());
			String value = tr.substring(startValue+START_VALUE.length(), stopValue);
			
			Integer broker;
			try {
				broker = Integer.valueOf(nf.parse(value).intValue());
			} catch (ParseException pe) {
				broker = Integer.valueOf("0");
			}
			t.setBroker(broker);
			
			// recuperem seguent startTr
			startTr = html.indexOf(START_TR, stopTr);
		}

		//privateLeague.setTeams(teams);
		
		return System.nanoTime()-start;
	}
}
